package com.ruoyi.system.phone.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.tel.domain.TelUseRoleConfig;
import com.ruoyi.system.tel.service.ITelUseRoleConfigService;
import com.ruoyi.system.telManage.service.ITelManageHistoryService;
import com.ruoyi.system.telMsg.domain.TelSendMsg;
import com.ruoyi.system.telMsg.service.ITelSendMsgService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.phone.mapper.TelManageNewMapper;
import com.ruoyi.system.phone.domain.TelManageNew;
import com.ruoyi.system.phone.service.ITelManageNewService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 手机卡管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-05
 */
@Service
public class TelManageNewServiceImpl implements ITelManageNewService {
    @Autowired
    private TelManageNewMapper telManageNewMapper;
    @Autowired
    private ITelManageHistoryService telManageHistoryService;
    @Autowired
    private ITelSendMsgService telSendMsgService;
    @Autowired
    private ITelUseRoleConfigService telUseRoleConfigService;

    /**
     * 查询手机卡管理
     *
     * @param id 手机卡管理主键
     * @return 手机卡管理
     */
    @Override
    public TelManageNew selectTelManageNewById(Long id) {
        return telManageNewMapper.selectTelManageNewById(id);
    }

    /**
     * 查询手机卡管理列表
     *
     * @param telManageNew 手机卡管理
     * @return 手机卡管理
     */
    @Override
    public List<TelManageNew> selectTelManageNewList(TelManageNew telManageNew) {
        return telManageNewMapper.selectTelManageNewList(telManageNew);
    }

    /**
     * 新增手机卡管理
     *
     * @param telManageNew 手机卡管理
     * @return 结果
     */
    @Override
    public int insertTelManageNew(TelManageNew telManageNew) {
        telManageNew.setCreateTime(DateUtils.getNowDate());
        int manage = telManageNewMapper.insertTelManageNew(telManageNew);
        if (manage == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", SecurityUtils.getUserId());
            params.put("operator", SecurityUtils.getUserNickName());
            params.put("status", "添加");
            params.put("telId", telManageNew.getId());
            params.put("reason", telManageNew.getTel());
            telManageHistoryService.addOperator(params);
        }
        return manage;
    }

    @Autowired
    private ISysDeptService deptService;

    /**
     * 批量导入
     *
     * @param list
     * @return
     */
    @Override
    public String bathInsert(List<TelManageNew> list) {
        Long userId = SecurityUtils.getUserId();
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        Map<String, Long> map = sysDepts.stream().collect(Collectors.toMap(s -> s.getDeptName(), s -> s.getDeptId()));
        if (CollectionUtils.isNotEmpty(list)) {
            for (TelManageNew telManageNew : list) {
                telManageNew.setCreateId(userId);
                telManageNew.setDeptId(map.get(telManageNew.getDeptName()));
                if (StringUtils.isEmpty(telManageNew.getCustodianType())) {
                    telManageNew.setCustodianType("企业卡");
                }
                this.insertTelManageNew(telManageNew);
            }
        }
        return "true";
    }

    /**
     * 修改手机卡管理
     *
     * @param telManageNew 手机卡管理
     * @return 结果
     */
    @Override
    public int updateTelManageNew(TelManageNew telManageNew) {
        telManageNew.setUpdateTime(DateUtils.getNowDate());
        telManageNew.setUpdateId(SecurityUtils.getUserId());

        int manage = telManageNewMapper.updateTelManageNew(telManageNew);
        if (manage == 1) {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", SecurityUtils.getUserId());
            params.put("operator", SecurityUtils.getUserNickName());
            params.put("status", "编辑");
            params.put("telId", telManageNew.getId());
            params.put("reason", telManageNew.getTel());
            telManageHistoryService.addOperator(params);
        }
        telManageNew.setCreateTime(DateUtils.getNowDate());
        return manage;
    }

    /**
     * 发送短信
     *
     * @param req
     * @return
     */
    @Override
    public JSONObject sendSMS(TelSendMsg req) {
        String category = req.getCategory();
        if (StringUtils.isEmpty(req.getCategory())) {
            throw new GlobalException("未分类卡位不可发送短信");
        }
        List<SysDictData> dictData = DictUtils.getDictCache("tel_sms_config");
        String uid = "";
        String userId = "";
        for (SysDictData key : dictData) {
            if (StringUtils.equals(key.getRemark(), category)) {
                uid = key.getDictLabel();
                userId = key.getDictValue();
                break;
            }
        }
        if (StringUtils.isEmpty(uid) || StringUtils.isEmpty(userId)) {
            throw new GlobalException("短信字典参数未配置");
        }
        String url = "http://mqtt.cc.maimaihao.com/api/msg/sendMsg";
        String body = HttpRequest
                .post(url)
                .header("uid", uid)
                .header("userId", userId)
                .body(JSONObject.toJSONString(req)).execute().body();
        JSONObject result = JSONObject.parseObject(body);
        req.setCreateId(SecurityUtils.getUserId());
        req.setCreateName(SecurityUtils.getUserNickName());
        req.setResult(body);
        req.setType("1");
        req.setCode(result.getString("code"));
        telSendMsgService.insertTelSendMsg(req);
        if (!StringUtils.equals(result.getString("code"), "200")) {
            throw new GlobalException(body);
        }
        return result;
    }

    /**
     * 批量删除手机卡管理
     *
     * @param ids 需要删除的手机卡管理主键
     * @return 结果
     */
    @Override
    public int deleteTelManageNewByIds(Long[] ids) {
        for (Long id : ids) {
            TelManageNew telManage = telManageNewMapper.selectTelManageNewById(id);
            Map<String, Object> params = new HashMap<>();
            params.put("userId", SecurityUtils.getUserId());
            params.put("operator", SecurityUtils.getUserNickName());
            params.put("status", "删除");
            params.put("telId", telManage.getId());
            params.put("reason", telManage.getTel());
            telManageHistoryService.addOperator(params);
        }

        return telManageNewMapper.deleteTelManageNewByIds(ids);
    }

    /**
     * 删除手机卡管理信息
     *
     * @param id 手机卡管理主键
     * @return 结果
     */
    @Override
    public int deleteTelManageNewById(Long id) {
        return telManageNewMapper.deleteTelManageNewById(id);
    }


    @Override
    @Transactional
    public int userStatus(TelManageNew telManage) {
        TelUseRoleConfig config = telUseRoleConfigService.selectTelUseRoleConfigById(telManage.getUseType());

        if (Objects.isNull(config)) {
            throw new GlobalException("配置类错误");
        }
        TelManageNew manage = telManageNewMapper.selectTelManageNewById(telManage.getId());
        if (Objects.isNull(manage)) {
            throw new GlobalException("未找到手机信息");
        }
        manage.setUseType(telManage.getUseType());
        manage.setUseTime(config.getRoleData());
        manage.setIsUse(config.getIsUse());
        manage.setUseImg(telManage.getUseImg());
        manage.setBindAccount(telManage.getBindAccount());
        manage.setUseRemark(telManage.getUseRemark());
        manage.setDownTime(new Date());

        Date useEndTime = DateUtils.getAddDayDateTime(config.getRoleData());
        manage.setUseEndTime(useEndTime);
        telManageNewMapper.updateTelManageNew(manage);

        // 操作记录
        String status = config.getType();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityUtils.getUserId());
        params.put("operator", SecurityUtils.getUserNickName());
        params.put("status", status);
        params.put("telId", telManage.getId());
        params.put("reason", telManage.getTel());
        params.put("bindAccount", telManage.getBindAccount());
        params.put("useTime", telManage.getUseTime());
        params.put("img", telManage.getUseImg());
        telManageHistoryService.addOperator(params);
        return 1;
    }

    public static void main(String[] args) {

    }

    @Override
    public int use(Long id) {
        TelManageNew telManage = telManageNewMapper.selectTelManageNewById(id);
        if (Objects.isNull(telManage)) {
            throw new GlobalException("未找到手机信息");
        }
        telManage.setUseType(0L);
        telManage.setUseTime(0);
        telManage.setIsUse(0);
        telManage.setUseImg("");
        telManage.setBindAccount("");
        telManage.setUseRemark("");

        telManageNewMapper.updateTelManageNew(telManage);
        String status = "转可用";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityUtils.getUserId());
        params.put("operator", SecurityUtils.getUserNickName());
        params.put("status", status);
        params.put("telId", telManage.getId());
        params.put("reason", telManage.getTel());
        telManageHistoryService.addOperator(params);
        return 1;
    }
}
